import {PageContainer} from '@ant-design/pro-components';
import React, {useEffect, useState} from 'react';
import {Button, Card, Descriptions, Divider, Form, Input, message, Image, Badge, Modal, InputNumber} from 'antd';
import {
  getInterfaceInfoByIdUsingGET,
  invokeInterfaceInfoUsingPOST,
} from '@/services/easyapi-backend/interfaceInfoController';
import {useModel, useParams, useRequest} from '@@/exports';
import moment from 'moment';
import ReactJson from 'react-json-view';
import VanillaJSONEditor from './VanillaJSONEditor';
import {addOrderUsingPOST} from "@/services/easyapi-backend/orderController";
import {getLoginUserUsingGET} from "@/services/easyapi-backend/userController";
import {getFreeInterfaceCountUsingPOST} from "@/services/easyapi-backend/userInterfaceInfoController";

/**
 * 查看接口文档
 * @constructor
 */
const Index: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<API.InterfaceInfo>();
  const [invokeRes, setInvokeRes] = useState<any>();
  const [invokeLoading, setInvokeLoading] = useState(false);
  const [orderModalOpen, setAddOrderModalOpen] = useState(false);
  const [orderCount, setOrderCount] = useState(1);
  const [totalAmount, setTotalAmount] = useState(1.0);
  const {initialState, setInitialState} = useModel('@@initialState');
  const params = useParams();
  const {loginUser} = initialState;
  const param = new Object();
  const [img, setImg] = useState(null);
  const [content, setContent] = useState({
    json: param,
    text: undefined,
  });

  // //  获取用户信息
  // const { data: currentUser, loading } = useRequest(() => {
  //   return getLoginUserUsingGET();
  // });

  // 点击购买
  const handleAddOrderOk = async () => {
    setLoading(true);
    try {
      const res = await addOrderUsingPOST({
        interfaceInfoId: data?.id,
        count: orderCount,
        userId: loginUser.id,
        totalAmount: totalAmount,
        charging: data?.charging,
      });
      if (res.code === 0) {
        message.success('订单创建成功');
      }
    } catch (e: any) {
      message.error('请求失败，' + e.message);
    }
    setLoading(false);
    loadData();
    setAddOrderModalOpen(false);
  };

  // 获取免费接口
  const getFreeInterface = async () => {
    setInvokeLoading(true);
    try {
      const res = await getFreeInterfaceCountUsingPOST({
        userId: loginUser.id,
        interfaceInfoId: data?.id,
        freeCount: 100,
      });
      if (res.data) {
        message.success('获取调用次数成功');
      } else {
        message.error('获取失败请重试');
      }
    } catch (e: any) {
      message.error('请求失败，' + e.message);
    }
    setInvokeLoading(false);
    loadData();
    return
  };

  const showAddOrderModal = () => {
    setTotalAmount(parseFloat((orderCount * parseFloat(data?.charging)).toFixed(2)));
    setAddOrderModalOpen(true);
  };

  // const getFreeInterface = async () => {
  //   setInvokeLoading(true);
  //   try {
  //     const res = await getFreeInterfaceCountUsingPOST({
  //       userId: loginUser.id,
  //       interfaceId: data?.id,
  //       lockNum: 100,
  //     });
  //     if (res.data) {
  //       message.success('获取调用次数成功');
  //     } else {
  //       message.error('获取失败请重试');
  //     }
  //   } catch (e: any) {
  //     message.error('请求失败，' + e.message);
  //   }
  //   setInvokeLoading(false);
  //   loadData();
  //   return
  // };

// 取消购买
  const handleAddOrderCancel = () => {
    setAddOrderModalOpen(false);
  };


  const onChangeOrderCount = (value: number) => {
    setOrderCount(value);
    setTotalAmount(parseFloat((value * parseFloat(data?.charging)).toFixed(2)));
    console.log('changed', value);
  };


  const loadData = async () => {
    if (!params.id) {
      message.error('参数不存在');
      return;
    }
    //百度接口
    if (Number(params.id) === 2) {
      param.size = '10';
    }
    //毒鸡汤接口
    if (Number(params.id) === 3) {
      param.charset = 'utf-8';
      param.encode = 'text';
    }
    //域名接口
    if (Number(params.id) === 4) {
      param.city = '';
    }
    if (Number(params.id) === 5) {
      param.ip = '';
    }
    //用户名接口
    if (Number(params.id) === 6) {
      param.username = 'zhangsan';
    }
    if (Number(params.id) === 7) {
      param.qq = '';
    }
    //域名接口
    if (Number(params.id) === 8) {
      param.domain = '';
    }
    setLoading(true);
    try {
      const res = await getInterfaceInfoByIdUsingGET({
        id: Number(params.id),
      });
      setData(res.data);
    } catch (error: any) {
      message.error('请求失败' + error.message);
    }
    setLoading(false);
  };

  useEffect(() => {
    loadData();
  }, []);

  const onFinish = async (values: any) => {
    if (!params.id) {
      message.error('接口不存在');
      return;
    }
    let jsonValue = JSON.stringify(content.json);
    // console.log("jsonvalue" + jsonValue)
    console.log(jsonValue);
    console.log(typeof jsonValue);
    //let replaceAfter;
    if (jsonValue == undefined || jsonValue == null || jsonValue === '') {
      jsonValue = JSON.parse(JSON.stringify(content.text));
    }
    setInvokeLoading(true);
    try {
      const res = await invokeInterfaceInfoUsingPOST({
        id: Number(params.id),
        userRequestParams: jsonValue,
      });
      let json1;
      console.log(res);
      if (res.code === 40100) {
        json1 = res;
        message.error('登录过期，请重新登录！');
      }
      if (params.id === '1') {
        setImg(res.data);
      } else {
        json1 = JSON.parse(res.data);
      }
      console.log(typeof json1);
      console.log(json1);
      setInvokeRes(json1);

      message.success('请求成功');
    } catch (error: any) {
      message.error('操作失败，' + error.message);
    }
    setInvokeLoading(false);
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  return (
    <>
      <PageContainer title={'查看接口文档'}>
        <Card>
          {data ? (
            <Descriptions
              title={data.name}
              bordered
              column={1}
              extra={
                data.charging > 0 ? (
                  <Button onClick={showAddOrderModal} type={"primary"}>购买</Button>
                ) : (
                  <Button onClick={getFreeInterface} type={"primary"}>获取</Button>
                )
              }>

              <Descriptions.Item label="描述" span={3}>
                {data.description}
              </Descriptions.Item>
              <Descriptions.Item label="接口状态" span={1}>
                <Badge
                  status={data.status === 1 ? 'success' : 'error'}
                  text={data.status === 1 ? '正常' : '下线'}
                />
              </Descriptions.Item>
              <Descriptions.Item label="单价" span={2}>{data.charging} 元</Descriptions.Item>
              <Descriptions.Item label="请求方法" span={1}>{data.method}</Descriptions.Item>
              <Descriptions.Item label="请求地址" span={3}>{data.url}</Descriptions.Item>
              <Descriptions.Item label="创建时间" span={1}>
                {moment(data.createTime).format('YYYY-MM-DD HH:mm:ss')}
              </Descriptions.Item>
              <Descriptions.Item label="更新时间" span={2}>
                {moment(data.updateTime).format('YYYY-MM-DD HH:mm:ss')}
              </Descriptions.Item>

              <Descriptions.Item label="请求头" span={3}>{data.requestHeader}</Descriptions.Item>
              <Descriptions.Item label="响应头" span={3}>
                {data.responseHeader}
              </Descriptions.Item>
              <Descriptions.Item label="请求参数" span={3}>
                <ReactJson name={false} src={JSON.parse(data.requestParams)}/>
              </Descriptions.Item>
            </Descriptions>
          ) : (
            <>接口不存在</>
          )}
        </Card>
        <Divider/>
        <Card title="在线测试">
          <Form name="invoke" layout={'vertical'} onFinish={onFinish} onFinishFailed={onFinishFailed}>
            <Form.Item label="请求参数" name="userRequestParams">
              <div className="my-editor">
                <VanillaJSONEditor content={content} onChange={setContent}/>
              </div>
              <Input.TextArea/>
            </Form.Item>

            <Form.Item wrapperCol={{span: 16}}>
              <Button type="primary" htmlType="submit">
                调用
              </Button>
            </Form.Item>
          </Form>
        </Card>
        <Divider/>
        <Card title={'返回结果'} loading={invokeLoading}>
          {img ? <Image width={200} src={img}/> : <ReactJson name={false} src={invokeRes}/>}
        </Card>
      </PageContainer>

      {/*点击购买后的弹窗*/}
      <Modal
        title="购买接口"
        open={orderModalOpen}
        onOk={handleAddOrderOk}
        onCancel={handleAddOrderCancel}
      >
        <Descriptions title={data?.name} size="small" layout="vertical" bordered>
          <Descriptions.Item label="接口状态">{data?.status ? '正常' : '关闭'}</Descriptions.Item>
          <Descriptions.Item label="计费">{data?.charging} 元 / 次</Descriptions.Item>
          {/*<Descriptions.Item label="接口剩余调用次数">{data?.availablePieces}次</Descriptions.Item>*/}
          <Descriptions.Item label="请求方法">{data?.method}</Descriptions.Item>
          <Descriptions.Item label="请求地址">{data?.url}</Descriptions.Item>
          <Descriptions.Item label="购买次数">
            <InputNumber
              min={1}
              max={100}
              defaultValue={1}
              onChange={onChangeOrderCount}
            />
          </Descriptions.Item>
        </Descriptions>
        <Divider/>
        <b>总计：{totalAmount}元</b>
      </Modal>
    </>
  );
};

export default Index;
